package datolib;

import java.io.*;
import java.net.*;

public class TcpGateway {


	private Socket socket;
	private InputStream reader;
	
	public TcpGateway() {
	
		this.socket = null;
		this.reader = null;
	}	
	        
	public TcpGateway(Socket s) {
		this.socket = s;
		try {
			this.reader = this.socket.getInputStream();
		} catch (IOException ioe) {
			this.reader = null;
		}
	}
	
	public SocketAddress getRemoteAddress() {
		return this.socket.getRemoteSocketAddress();
	}

	public InputStream getInputStream() throws IOException {
		return this.socket.getInputStream();
	}
	
	public OutputStream getOutputStream() throws IOException {
		return this.socket.getOutputStream();
	}

	public XmlMessage readNextMessage() throws IOException {

		while (true) {
			
			int bufferLength = this.reader.available();

			if (bufferLength == 0) {
				continue;
			}


			byte[] buffer = new byte[bufferLength];
			this.reader.read(buffer);
			return new XmlMessage(new String(buffer, 0, buffer.length, "ISO8859_1"));	
		}
	}

	public void close() throws IOException {
		this.reader.close();
		this.socket.close();
	}

	public boolean afl(String msg) {
		return this.write(XmlMessageBuilder.afl(msg));
	}
	
	public boolean asl(int uipLength, String cimlFile) {
		return this.write(XmlMessageBuilder.asl(uipLength, cimlFile));
	}

	public boolean unkownMessage() {
		return this.write("UKN");
	}
	
	public boolean unkownMessage(String message) {
		return this.write("UKN:" + message);
	}
	
	public boolean scp(String control, String property, String value) {
		return this.write(XmlMessageBuilder.scp(control, property, value));
	}
	
	public boolean iss() {
		return this.write(XmlMessageBuilder.iss());
	}
	
	public boolean ifl() {
		return this.write(XmlMessageBuilder.ifl());
	}

	public boolean msg(String message) {
		return this.write(XmlMessageBuilder.msg(message));
	}

	private boolean write(String str) {
		
		if (this.socket == null)
    		return false;
    		
    	try {
    		PrintStream socketOut = new PrintStream(this.socket.getOutputStream());
    		socketOut.print(str);
 			socketOut.flush();
    		return true;
    	} catch (IOException ioe) {
    		return false;
    	}
	}

	public boolean write(byte[] array, int off, int length) {
    
    	if (this.socket == null)
    		return false;
    
    	try {
    		PrintStream ps = new PrintStream(this.socket.getOutputStream());
    		ps.write(array, off, length);
    		ps.flush();
    		return true;
    	} catch (IOException ioe) {
    		return false;
    	}

    }   
}
